/*
 * @Author: asushiye
 * @Date: 2020-07-07 09:41:13
 * @Commit: Table Array filtering, creating, editing, deleting, and querying operations
 */
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AfArrayService {
  constructor() {}

  // 过滤 - 对整个table进行过滤，返回符合的行数据
  public filterTable<T>(filterString: any, tableData: T[] = [], columns: any[] = []) {
    // console.log(JSON.stringify(tableFilter));
    let filteredData = tableData.slice(0, tableData.length);

    if (filterString) {
      const tempArray: any[] = [];
      filteredData.forEach((item: any) => {
        let flag = false;
        columns.forEach((column: any) => {
          console.log(column.index);
          if (column.index !== '') {
            const itemString = JSON.stringify(item[column.index]);
            if (itemString) {
              if (itemString.match(filterString)) {
                flag = true;
              }
            }
          }
        });
        if (flag) {
          tempArray.push(item);
        }
      });
      filteredData = tempArray;
    }
    // console.log(filteredData);
    return filteredData;
  }

  // 过滤 - 对一个列进行过滤，返回符合的行数据
  public filterColumn<T>(filterString: any, tableData: T[] = [], column: string) {
    // console.log(JSON.stringify(tableFilter));
    let filteredData = tableData.slice(0, tableData.length);

    if (filterString) {
      const tempArray: any[] = [];
      filteredData.forEach((item: any) => {
        let flag = false;
        const itemString = JSON.stringify(item[column]);
        if (itemString) {
          if (itemString.match(filterString)) {
            flag = true;
          }
        }
        if (flag) {
          tempArray.push(item);
        }
      });
      filteredData = tempArray;
    }
    // console.log(filteredData);
    return filteredData;
  }

  // 删除数组 -  按selected元素删除sources数组，数组元素结构一致
  deleteArray(sources: any[], selected: any[], clear: boolean = true) {
    selected.forEach(row => {
      const i = sources.indexOf(row);
      if (i >= 0) {
        sources.splice(i, 1);
      }
    });
    if (clear) {
      selected = [];
    }
    return sources;
  }

  // 删除数组 -  按selected元素删除sources数组，数组元素结构一致
  deleteElement(sources: any[], element: any) {
    const i = sources.indexOf(element);
    if (i >= 0) {
      sources.splice(i, 1);
    }
    return sources;
  }
  // 删除数组 -  按selected元素删除sources数组，数组元素结构一致
  existElement(sources: any[], value: any) {
    let isExist = false;
    sources.forEach(item => {
      if (item === value) {
        isExist = true;
        return;
      }
    });
    return isExist;
  }
}
